package com.wtwd.campus.hxy.service.impl;

import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.Command;
import com.wtwd.campus.entity.DeviceSOSList;
import com.wtwd.campus.hxy.constant.RespCode;
import com.wtwd.campus.hxy.dao.DeviceMapper;
import com.wtwd.campus.hxy.dao.HxyCommandRecordMapper;
import com.wtwd.campus.hxy.dao.HxyPhoneMapper;
import com.wtwd.campus.hxy.dao.OfflineBufferCmdMapper;
import com.wtwd.campus.hxy.entity.CommandRecord;
import com.wtwd.campus.hxy.entity.DeviceInfo;
import com.wtwd.campus.hxy.entity.DeviceWhiteList;
import com.wtwd.campus.hxy.model.vo.ResultVO;
import com.wtwd.campus.hxy.service.HxyPhoneService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.CommandNumberUtil;
import com.wtwd.campus.utils.CommandSendUtils;
import com.wtwd.campus.utils.ReceiverUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.security.auth.login.FailedLoginException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mjy
 * @date 2021/07/27
 * @description
 */
@Service
public class HxyPhoneServiceImpl implements HxyPhoneService {

    @Resource
    private HxyPhoneMapper hxyPhoneMapper;
    @Autowired
    private CommandSendUtils commandSendUtils;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private HxyCommandRecordMapper commandRecordMapper;
    @Autowired
    private OfflineBufferCmdMapper offlineBufferCmdMapper;
    @Autowired
    private RedisService redisService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Object setAllWhite(List<Map> numberList, String imei) {
        if (numberList != null && numberList.size() > 17) {
            return ResultVO.error(RespCode.DEVICE_WHITE_LIST);
        }
        //删除原来所有数据(包括离线的待发送数据和发送失败的数据)
        DeviceInfo deviceInfo = deviceMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return ResultVO.error(RespCode.DEVICE_NO_EXIST);
        }
        hxyPhoneMapper.delDeviceAllWhiteCall(deviceInfo.getDeviceId());
        List<Map<String,Object>> sendList = new ArrayList<>();
        List<Map<String,Object>> saveList = new ArrayList<>();
        String commandNumber = CommandNumberUtil.getCurTime();
        // 固定循环17次，后面的表示为空,确保号码正确
        for (int i = 0; i < 17; i++) {
            if (numberList.size() < i + 1) {
                Map<String,Object> map = new HashMap<>();
                map.put("name","");
                map.put("phone","");
                map.put("sequence",i + 7);
                sendList.add(map);
            } else {
                // 传过来的，需要保存到数据库，且需要拿实际数据发送
                Map<String,Object> map = new HashMap<>();
                map.put("name",numberList.get(i).get("disname"));
                map.put("phone",numberList.get(i).get("number"));
                map.put("sequence",i + 7);
                sendList.add(map);
                saveList.add(map);
            }
        }
        // 保存数据
        hxyPhoneMapper.saveWhiteCall(deviceInfo.getDeviceId(),commandNumber,saveList);
        // 发送数据
        boolean isSend = commandSendUtils.setAllWhiteCall(sendList,imei,commandNumber,true,-3,false);
        return isSend ? ResultVO.okWithOutData() : ResultVO.error(RespCode.FAIL);
    }

    @Override
    public Object setFamilyPhone(String imei, List<Map> numberList) {
        //查看设备是否在线
        boolean online = commandSendUtils.deviceOnline(imei);
        if (!online) {//离线不做任何操作
            return ResultVO.error(RespCode.DEVICE_IS_OFFLINE);
        }
        if (numberList != null && numberList.size() > 3) {
            return ResultVO.error(RespCode.DEVICE_FAMILY_LIST);
        }
        DeviceInfo deviceInfo = deviceMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return ResultVO.error(RespCode.DEVICE_NO_EXIST);
        }
        // 1.清除设备原有的
        hxyPhoneMapper.clearAffection(deviceInfo.getDeviceId());
        ArrayList<DeviceWhiteList> whiteList = new ArrayList<>();
        List<Map<String, Object>> sendList = new ArrayList<>();
        String commandNumber = CommandNumberUtil.getCurTime();
        for (int i = 0; i < 3; i++) {
            Map<String, Object> map = new HashMap<>();
            if (numberList.size() < i + 1) {
                map.put("name", "");
                map.put("phone", "");
                map.put("sequence", i + 4);
                sendList.add(map);
            } else {
                DeviceWhiteList white = new DeviceWhiteList();
                Map data = numberList.get(i);
                white.setWhiteName((String) data.get("familyName"));
                white.setWhitePhone((String) data.get("familyNumber"));
                white.setSequence(i + 4);
                white.setCommandNumber(commandNumber);
                white.setIsAffection(1);
                white.setDeviceId(deviceInfo.getDeviceId());
                // 2- 待添加
                white.setStatus(2);
                whiteList.add(white);
                map.put("name", (String) data.get("familyName"));
                map.put("phone", (String) data.get("familyNumber"));
                map.put("sequence", i + 4);
                sendList.add(map);
            }
        }
        if (whiteList != null && whiteList.size() > 0) {
            hxyPhoneMapper.bathAddWhiteList(whiteList);
        }
        boolean isSend = commandSendUtils.setAllWhiteCall(sendList, imei, commandNumber, true, -3, false);
        return isSend ? ResultVO.okWithOutData() : ResultVO.error(RespCode.FAIL);
    }

    @Override
    public Object setSOSPhone(String imei, List<String> phoneList) {
        // phoneList是按照接口传入的号码顺序排序的。客户不带SOS号码名，因此给默认值。
        boolean isOnline = commandSendUtils.deviceOnline(imei);
        if (!isOnline) {
            return ResultVO.error(RespCode.DEVICE_IS_OFFLINE);
        }
        // 1.校验设备是否存在
        DeviceInfo deviceInfo = deviceMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return ResultVO.error(RespCode.DEVICE_NO_EXIST);
        }
        // 2.清除掉设备原有的
        hxyPhoneMapper.clearSOSPhone(deviceInfo.getDeviceId());
        // 3.构建数据（固定三层循环，因为发送到设备端是需要固定三个号码的；如果phoneList为空，则不出入数据库，但是还是要发送指令）
        List<DeviceSOSList> deviceSOSList = new ArrayList<>();
        List<DeviceSOSList> sendList = new ArrayList<>();
        String commandNumber = CommandNumberUtil.getCurTime();
        for (int i = 0; i < 3; i++) {
            DeviceSOSList sos = new DeviceSOSList();
            if (phoneList.size() < i + 1) {
                sos.setSosName("");
                sos.setSosPhone("");
                sos.setSequence(i + 1);
                sos.setCommandNumber(commandNumber);
                sos.setDeviceId(deviceInfo.getDeviceId());
                sendList.add(sos);
            } else {
                sos.setSosName("SOS号码" + i);
                sos.setSosPhone(phoneList.get(i));
                sos.setSequence(i + 1);
                sos.setCommandNumber(commandNumber);
                sos.setDeviceId(deviceInfo.getDeviceId());
                // 2- 待添加
                sos.setStatus(2);
                sendList.add(sos);
                deviceSOSList.add(sos);
            }
        }
        if (phoneList.size() > 0) {
            // 3.插入数据
            hxyPhoneMapper.batchSaveSOSPhone(deviceSOSList);
        }
        // 4.发送指令
        boolean isSend = commandSendUtils.setAllSosCall(sendList, imei, commandNumber, true, -3, false);
        return isSend ? ResultVO.okWithOutData() : ResultVO.error(RespCode.FAIL);
    }

    @Override
    public ResultVO getFamilyPhoneAndSOSPhone(String imei) {
        // 1.校验设备是否存在
        DeviceInfo deviceInfo = deviceMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return ResultVO.error(RespCode.DEVICE_NO_EXIST);
        }
        List<DeviceWhiteList> whiteLists = hxyPhoneMapper.getAffectionPhoneList(deviceInfo.getDeviceId());
        List<DeviceSOSList> sosLists = hxyPhoneMapper.getSosList(deviceInfo.getDeviceId());
        // 构建结果集
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> familyNumberList = new ArrayList<>();
        for (DeviceWhiteList white : whiteLists) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", String.valueOf(white.getId()));
            map.put("familyName", white.getWhiteName());
            map.put("familyNumber", white.getWhitePhone());
            familyNumberList.add(map);
        }
        List<Map<String, Object>> sosNumberList = new ArrayList<>();
        for (DeviceSOSList sos : sosLists) {
            Map<String, Object> map = new HashMap<>();
            map.put("sosNumber", sos.getSosPhone());
            sosNumberList.add(map);
        }
        result.put("familyNumberList", familyNumberList);
        result.put("sosNumber", sosNumberList);
        return ResultVO.ok(result);
    }

    @Override
    public ResultVO getWhiteCallList(String imei) {
        // 1.校验设备是否存在
        DeviceInfo deviceInfo = deviceMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return ResultVO.error(RespCode.DEVICE_NO_EXIST);
        }
        List<DeviceWhiteList> whiteLists = hxyPhoneMapper.getWhiteCallList(deviceInfo.getDeviceId());
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (DeviceWhiteList white : whiteLists) {
            Map<String, Object> map = new HashMap<>();
            map.put("number", white.getWhitePhone());
            map.put("disname", white.getWhiteName());
            resultList.add(map);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("numberList", resultList);
        return ResultVO.ok(result);
    }

    @Override
    public Object getDeviceSimCard(String imei) {
        // 1.校验设备是否存在
        DeviceInfo deviceInfo = deviceMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return ResultVO.error(RespCode.DEVICE_NO_EXIST);
        }
        String simCard = deviceInfo.getSimCard();
        Map<String, Object> result = new HashMap<>();
        result.put("code", "0");
        result.put("message", "操作成功");
        result.put("number", simCard);
        result.put("imei", imei);
        return result;
    }
}
